﻿using System.Collections.Generic;
using BFlatCompile.Nodes;

namespace BFlatCompile.Serializer
{
	internal static class Phase03PopulateParentLookup
	{
		public static void Do(IList<Namespace> rootNamespaces, Dictionary<object, object> parents)
		{
			foreach (Namespace ns in rootNamespaces)
			{
				parents[ns] = null;
				PopulateParentLookup(parents, ns);
			}
		}

		private static void PopulateParentLookup(Dictionary<object, object> lookup, Namespace ns)
		{
			foreach (Namespace subnamespace in ns.Namespaces)
			{
				lookup[subnamespace] = ns;
				PopulateParentLookup(lookup, subnamespace);
			}

			foreach (Class c in ns.Classes)
			{
				lookup[c] = ns;
				PopulateParentLookup(lookup, c);
			}
		}

		private static void PopulateParentLookup(Dictionary<object, object> lookup, Class c)
		{
			foreach (Class nestedClass in c.NestedClasses)
			{
				lookup[nestedClass] = c;
				PopulateParentLookup(lookup, nestedClass);
			}

			foreach (Field f in c.Fields)
			{
				lookup[f] = c;
			}

			foreach (Method m in c.Methods)
			{
				lookup[m] = c;
			}

			foreach (Property p in c.Properties)
			{
				lookup[p] = c;
			}

			foreach (Constructor x in c.Constructors)
			{
				lookup[x] = c;
			}
		}
	}
}
